﻿# encoding:utf-8
# 为清除 user 表的重复的 puid 而做的工程
import time, json
from UniqueDbBase import *
from UniqueDbUser import *
import sys
sys.path.append("../..")
from wxpyBase import *

# 清理 user 表中重复的 puid 到 user_del 表中
def updatePuid(dbd, puid):
    users = dbGetUserAll(dbd, puid)
    if users is None or len(users)==0:
        return False
    # printJson(users)
    # 找出最小ID
    minUser = users[0]
    for u in users:
        if(u['id']<minUser['id']):
            minUser = u
    
    attrs = []

    # 每个数据取最后更新的值
    nick_name = dbGetUserAttributeLatest(dbd, puid, 'nick_name')
    if nick_name is not None and len(nick_name)>0:
        minUser['nick_name'] = nick_name
        attrs.append('nick_name')
    
    remark_name = dbGetUserAttributeLatest(dbd, puid, 'remark_name')
    if remark_name is not None and len(remark_name)>0:
        minUser['remark_name'] = remark_name
        attrs.append('remark_name')
    
    avatar = dbGetUserAttributeLatest(dbd, puid, 'avatar')
    if avatar is not None and len(avatar)>0:
        minUser['avatar'] = avatar
        attrs.append('avatar')
    
    # 直接用最新的一个 group
    minUser['is_group'] = users[0]['is_group']
    attrs.append('is_group')
    
    # 更新回去
    if len(attrs)>0:
        if dbUpdateUserById(dbd, minUser, attrs):
            moveUsersExceptId(dbd, users, minUser['id'])
            return True
    
    return False

# 将用户从 user 表移到 user_del 中，除了指定ID
def moveUsersExceptId(dbd, users, id):
    for u in users:
        if u['id']!=id:
            if dbAddUserDel(dbd, u):
                dbDelUser(dbd, u['id'])

# main
def main():
    dbd = dbData()
    try:
        puids = dbGetAllRepeatPuids(dbd)
        if puids is None or len(puids)==0:
            return

        for puid in puids:
            updatePuid(dbd, puid)
    except Exception as e:
        dealException()
        logError('main err: '+str(e))
    finally:
        closeDb(dbd)

if __name__ == '__main__':
    timeStart = time.perf_counter()
    main()
    timeEnd = time.perf_counter()
    logError('main spend time: '+str(timeEnd-timeStart))